package com.hanson.service;

import com.hanson.common.exception.BusinessException;
import com.hanson.common.util.BusinessUtil;
import com.hanson.entity.CartBean;
import com.hanson.entity.GoodsAttrValueBean;
import com.hanson.entity.GoodsBean;
import com.hanson.entity.UserBean;
import com.hanson.mapper.CartBeanMapper;
import com.hanson.mapper.GoodsAttrValueBeanMapper;
import com.hanson.mapper.GoodsBeanMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class CartService {
    @Autowired
    private CartBeanMapper cartBeanMapper;
    @Autowired
    private GoodsBeanMapper goodsBeanMapper;
    @Autowired
    private GoodsAttrValueBeanMapper goodsAttrValueBeanMapper;
    @Autowired
    private UserService userService;

    @Transactional(rollbackFor = Exception.class)
    public void addCart(String openId, CartBean cartBean) {
        cartBean.setCreateDate(new Date());
        cartBean.setOpenId(openId);
        List<GoodsAttrValueBean> goodsAttrValueBeanList = goodsAttrValueBeanMapper.selectByByGoodsIdAndSuk(cartBean.getGoodsId(), cartBean.getGoodsAttr());
        UserBean userBean = userService.selectByOpenId(openId);
        if (null == userBean) {
            throw new BusinessException("当前用户未登录，请先登录");
        }
        if (CollectionUtils.isEmpty(goodsAttrValueBeanList)) {
            log.error("【商品 goodsId = {} suk = {} 规格为空】", cartBean.getGoodsId(), cartBean.getGoodsAttr());
            GoodsBean goodsBean = goodsBeanMapper.selectByPrimaryKey(cartBean.getGoodsId());
            int price = userBean.getIsVip() == 1 ? goodsBean.getVipPrice() : goodsBean.getPrice();
            cartBean.setTotalPrice(price * cartBean.getAddNum());
        } else {
            int price = userBean.getIsVip() == 1 ? Integer.parseInt(goodsAttrValueBeanList.get(0).getVipPrice()) : Integer.parseInt(goodsAttrValueBeanList.get(0).getPrice());
            cartBean.setTotalPrice(price * cartBean.getAddNum());
        }
        List<CartBean> cartBeanList = cartBeanMapper.selectByOpenId(openId);
        if (CollectionUtils.isEmpty(cartBeanList)) {
            cartBeanMapper.insert(cartBean);
        } else {
            boolean find = false;
            for (CartBean returnBean : cartBeanList) {
                //商品和属性一样 进行合并
                if (returnBean.getGoodsId().equals(cartBean.getGoodsId())
                        && returnBean.getGoodsAttr().equals(cartBean.getGoodsAttr())) {
                    returnBean.setAddNum(returnBean.getAddNum() + cartBean.getAddNum());
                    returnBean.setTotalPrice(returnBean.getTotalPrice() + cartBean.getTotalPrice());
                    cartBeanMapper.updateByPrimaryKey(returnBean);
                    find = true;
                    break;
                }
            }
            if(!find){
                cartBeanMapper.insert(cartBean);
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void updateCart(String openId, CartBean cartBean) {
        CartBean returnBean = cartBeanMapper.selectByPrimaryKey(cartBean.getId());
        if (null == returnBean || !returnBean.getOpenId().equals(openId)) {
            throw new BusinessException("参数错误");
        }
        List<GoodsAttrValueBean> goodsAttrValueBeanList = goodsAttrValueBeanMapper.selectByByGoodsIdAndSuk(cartBean.getGoodsId(), cartBean.getGoodsAttr());
        UserBean userBean = userService.selectByOpenId(openId);
        if (null == userBean) {
            throw new BusinessException("当前用户未登录，请先登录");
        }
        if (CollectionUtils.isEmpty(goodsAttrValueBeanList)) {
            log.error("【商品 goodsId = {} suk = {} 规格为空】", cartBean.getGoodsId(), cartBean.getGoodsAttr());
            GoodsBean goodsBean = goodsBeanMapper.selectByPrimaryKey(cartBean.getGoodsId());
            int price = userBean.getIsVip() == 1 ? goodsBean.getVipPrice() : goodsBean.getPrice();
            cartBean.setTotalPrice(price * cartBean.getAddNum());
        } else {
            int price = userBean.getIsVip() == 1 ? Integer.parseInt(goodsAttrValueBeanList.get(0).getVipPrice()) : Integer.parseInt(goodsAttrValueBeanList.get(0).getPrice());
            cartBean.setTotalPrice(price * cartBean.getAddNum());
        }
        cartBean.setCreateDate(returnBean.getCreateDate());
        cartBeanMapper.updateByPrimaryKey(cartBean);
    }

    public List<CartBean> selectByOpenId(String openId, ModelMap modelMap) {
        List<CartBean> cartBeanList = cartBeanMapper.selectByOpenId(openId);
        final int[] totalCount = {0};
        final int[] totalPrice = {0};
        if (CollectionUtils.isNotEmpty(cartBeanList)) {
            cartBeanList.stream().forEach(c -> {
                GoodsBean goodsBean = goodsBeanMapper.selectByPrimaryKey(c.getGoodsId());
                if (null != goodsBean) {
                    c.setImage(goodsBean.getImage());
                    c.setGoodsName(goodsBean.getGoodsName());
                }
                c.setWebTotalPrice(BusinessUtil.getWebAmount(c.getTotalPrice()));
                totalCount[0] += c.getAddNum();
                totalPrice[0] += c.getTotalPrice();
            });
        }
        modelMap.put("totalCount", totalCount[0]);
        modelMap.put("totalPrice", BusinessUtil.getWebAmount(totalPrice[0]));
        return cartBeanList;
    }

    public int countByOpenId(String openId) {
        Integer count = cartBeanMapper.countByOpenId(openId);
        return null == count ? 0 : count;
    }

    @Transactional(rollbackFor = Exception.class)
    public void deleteCart(String[] ids) {
        Arrays.stream(ids).forEach(c -> {
            cartBeanMapper.deleteByPrimaryKey(Integer.parseInt(c));
        });
    }
}
